//
//  CY_DetailViewController.m
//  悦享
//
//  Created by dllo on 16/3/19.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "CY_DetailViewController.h"
#import "SongsModel.h"
#import <UIImageView+WebCache.h>
#import <UIButton+WebCache.h>
#import "CY_DetailTableViewCell.h"
#import "PlayMusicViewController.h"
#import "AuditionListModel.h"
#import "PlayMusicHelp.h"
#import "APPTools.h"
#import <MBProgressHUD.h>

const CGFloat BackGroupHeight = 250;

@interface CY_DetailViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, retain) UITableView *detailTableView;
/// tableView 头视图上的图片
@property (nonatomic, retain) UIImageView *imgView;
/// 保存歌曲的数组
@property (nonatomic, retain) NSMutableArray *songsArr;
/**< 页面标题 */
@property (nonatomic, retain) UILabel *titleLabel;

@property (nonatomic, retain) UIView *footerView;

@property (nonatomic, assign) BOOL isUp;

@property (nonatomic, retain) MBProgressHUD *progressView;


@end

@implementation CY_DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"48ae0dcf1e9aef7108fcbe77c0072647.jpg"]];
    
    self.songsArr = [NSMutableArray array];
    
    [self createTabelView];
    
    [self dataHandle];
    
    _isUp = 1;
}

#pragma mark - 创建TableView
- (void)createTabelView {
    
    self.detailTableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    _detailTableView.delegate = self;
    _detailTableView.dataSource = self;
    _detailTableView.backgroundColor = [UIColor clearColor];
    _detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _detailTableView.contentInset = UIEdgeInsetsMake(BackGroupHeight, 0, 0, 0);
    [self.view addSubview:_detailTableView];
    
    /**
     *  设置大的图片
     */
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -BackGroupHeight, SREEN_WIDTH, BackGroupHeight)];
    [_imgView sd_setImageWithURL:[NSURL URLWithString:_urlString] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
    [_detailTableView addSubview:_imgView];
    
    // 返回按钮
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(10, 20, 30, 30);
    [back setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:(UIControlStateNormal)];
    [self.view addSubview:back];
    [back addTarget:self action:@selector(backAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 用Label 设置标题
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    _titleLabel.text = @"歌曲";
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.textColor = [UIColor blackColor];
    self.navigationItem.titleView = _titleLabel;
    
    
    // 注册
    [_detailTableView registerClass:[CY_DetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    
    self.progressView = [[MBProgressHUD alloc] initWithView:self.view];
    self.progressView.labelText = @"加载中...";
    self.progressView.mode = MBProgressHUDModeIndeterminate;
    self.progressView.backgroundColor = [UIColor colorWithRed:0.55 green:0.55 blue:0.55 alpha:0.5];
    [self.progressView show:YES];
    [self.view addSubview:_progressView];
    
    // 去掉黑线
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        NSArray *list = self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *View = (UIImageView *)obj;
                View.hidden = YES;
            }
        }
    }
    
    
}

#pragma mark - 返回按钮点击方法
- (void)backAction:(UIButton *)button {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _songsArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CY_DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.selectionStyle = UITableViewScrollPositionNone;
    cell.backgroundColor = [UIColor clearColor];
    NSInteger count = indexPath.row + 1;
    NSString *str = [NSString stringWithFormat:@"%ld", count];
    cell.numLabel.text = str;
    
    
    SongsModel *model = _songsArr[indexPath.row];
    cell.model = model;
    
    return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
    
}

#pragma mark tableView 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    

    PlayMusicViewController *playVc = [[PlayMusicViewController alloc] init];
     SongsModel *model = _songsArr[indexPath.row];
    AuditionListModel *listModel = model.auditionListArr[0];
    
    playVc.imgViewUrl = model.picUrl;
    playVc.nameString = model.name;
    playVc.musicUrl = listModel.url;
    playVc.index = indexPath.row;
    playVc.playArr = _songsArr;
        
    playVc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
    [self presentViewController:playVc animated:YES completion:^{
        
    }];
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat yOffset = scrollView.contentOffset.y;
    CGFloat xOffset = (yOffset + BackGroupHeight) * 2;
    if (yOffset < -BackGroupHeight) {
        CGRect rect = _imgView.frame;
        rect.origin.y = yOffset;
        rect.size.height = -yOffset;
        rect.origin.x = xOffset;
        rect.size.width = self.view.frame.size.width + fabs(xOffset) * 2;
        _imgView.frame = rect;
    }
    
    CGFloat alpha = (yOffset + BackGroupHeight) / BackGroupHeight;
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor colorWithRed:0.13 green:0.13 blue:0.13 alpha:1.0] colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
    
    _titleLabel.alpha = alpha;
}

- (UIImage *)imageWithColor:(UIColor *)color {
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
    
}
#pragma mark - 数据处理
- (void)dataHandle {
    
    NSString *path = [NSString stringWithFormat:@"http://api.songlist.ttpod.com/songlists/%@?app=ttpod&v=v8.1.5.2016022418&user_id=0&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=8.4.1&active=1&net=2&openudid=2b2eba0e983843cf5ebcfa76b63e1682221e74ef&idfa=C142307D-73E9-409F-88B5-2F7B28503941&utdid=VkKgUwkPrlsDAINyD9AzAIoe&alf=201200&bundle_id=com.ttpod.music&latitude=&longtitude=", _musicID];
    
    [APPTools GETWithURL:path par:nil success:^(id responseObject) {
        
        NSArray *tempArr = responseObject[@"songs"];
        self.songsArr = [SongsModel baseModelHandleWithArr:tempArr];
        NSLog(@"%ld", _songsArr.count);
        
        [_detailTableView reloadData];
        
        [_progressView removeFromSuperview];
        
    } filed:^(NSError *error) {
        
    }];
    
}

//- (void)viewWillAppear:(BOOL)animated {
//    
//    self.navigationController.navigationBar.translucent = YES;
//    
//    self.tabBarController.tabBar.translucent = YES;
//    
//}

  

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
